﻿using System;
using System.Collections.Generic;
using System.Linq;

// 商品类
public class Product
{
    public string ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }

    public Product(string productId, string name, decimal price)
    {
        ProductId = productId;
        Name = name;
        Price = price;
    }

    public override string ToString()
    {
        return $"商品ID: {ProductId}, 名称: {Name}, 单价: {Price:C}";
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Product other = (Product)obj;
        return ProductId == other.ProductId;
    }

    public override int GetHashCode()
    {
        return ProductId.GetHashCode();
    }
}

// 客户类
public class Customer
{
    public string CustomerId { get; set; }
    public string Name { get; set; }

    public Customer(string customerId, string name)
    {
        CustomerId = customerId;
        Name = name;
    }

    public override string ToString()
    {
        return $"客户ID: {CustomerId}, 姓名: {Name}";
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Customer other = (Customer)obj;
        return CustomerId == other.CustomerId;
    }

    public override int GetHashCode()
    {
        return CustomerId.GetHashCode();
    }
}

// 订单明细类
public class OrderDetail
{
    public Product Product { get; set; }
    public int Quantity { get; set; }

    public OrderDetail(Product product, int quantity)
    {
        Product = product;
        Quantity = quantity;
    }

    public decimal Amount => Product.Price * Quantity;

    public override string ToString()
    {
        return $"{Product}, 数量: {Quantity}, 小计: {Amount:C}";
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        OrderDetail other = (OrderDetail)obj;
        return Product.Equals(other.Product);
    }

    public override int GetHashCode()
    {
        return Product.GetHashCode();
    }
}

// 订单类
public class Order : IComparable<Order>
{
    public string OrderId { get; set; }
    public Customer Customer { get; set; }
    public DateTime OrderDate { get; set; }
    public List<OrderDetail> Details { get; set; } = new List<OrderDetail>();

    public decimal TotalAmount => Details.Sum(d => d.Amount);

    public Order(string orderId, Customer customer, DateTime orderDate)
    {
        OrderId = orderId;
        Customer = customer;
        OrderDate = orderDate;
    }

    public void AddDetail(OrderDetail detail)
    {
        if (Details.Contains(detail))
        {
            throw new ArgumentException("订单中已存在相同的商品明细");
        }
        Details.Add(detail);
    }

    public void RemoveDetail(Product product)
    {
        var detail = Details.FirstOrDefault(d => d.Product.Equals(product));
        if (detail != null)
        {
            Details.Remove(detail);
        }
        else
        {
            throw new ArgumentException("订单中不存在指定的商品");
        }
    }

    public override string ToString()
    {
        string detailsStr = string.Join("\n  ", Details.Select(d => d.ToString()));
        return $"订单号: {OrderId}, 客户: {Customer}, 订单日期: {OrderDate:yyyy-MM-dd}\n" +
               $"  明细:\n  {detailsStr}\n" +
               $"  总金额: {TotalAmount:C}";
    }

    public override bool Equals(object obj)
    {
        if (obj == null || GetType() != obj.GetType())
            return false;

        Order other = (Order)obj;
        return OrderId == other.OrderId;
    }

    public override int GetHashCode()
    {
        return OrderId.GetHashCode();
    }

    public int CompareTo(Order other)
    {
        return OrderId.CompareTo(other.OrderId);
    }
}

// 订单服务类
public class OrderService
{
    private List<Order> orders = new List<Order>();

    // 添加订单
    public void AddOrder(Order order)
    {
        if (orders.Contains(order))
        {
            throw new ArgumentException("订单已存在，不能重复添加");
        }
        orders.Add(order);
    }

    // 删除订单
    public void RemoveOrder(string orderId)
    {
        var order = orders.FirstOrDefault(o => o.OrderId == orderId);
        if (order == null)
        {
            throw new ArgumentException($"找不到订单号为 {orderId} 的订单");
        }
        orders.Remove(order);
    }

    // 修改订单（替换整个订单）
    public void UpdateOrder(Order order)
    {
        var existingOrder = orders.FirstOrDefault(o => o.OrderId == order.OrderId);
        if (existingOrder == null)
        {
            throw new ArgumentException($"找不到订单号为 {order.OrderId} 的订单");
        }
        orders.Remove(existingOrder);
        orders.Add(order);
    }

    // 查询所有订单
    public List<Order> GetAllOrders()
    {
        return orders.OrderBy(o => o.OrderId).ToList();
    }

    // 按订单号查询
    public List<Order> QueryByOrderId(string orderId)
    {
        var query = from o in orders
                    where o.OrderId == orderId
                    orderby o.TotalAmount
                    select o;
        return query.ToList();
    }

    // 按商品名称查询
    public List<Order> QueryByProductName(string productName)
    {
        var query = from o in orders
                    from d in o.Details
                    where d.Product.Name.Contains(productName)
                    orderby o.TotalAmount
                    select o;
        return query.Distinct().ToList();
    }

    // 按客户查询
    public List<Order> QueryByCustomer(Customer customer)
    {
        var query = from o in orders
                    where o.Customer.Equals(customer)
                    orderby o.TotalAmount
                    select o;
        return query.ToList();
    }

    // 按订单金额范围查询
    public List<Order> QueryByAmountRange(decimal minAmount, decimal maxAmount)
    {
        var query = from o in orders
                    where o.TotalAmount >= minAmount && o.TotalAmount <= maxAmount
                    orderby o.TotalAmount
                    select o;
        return query.ToList();
    }

    // 排序方法（默认按订单号排序）
    public void SortOrders()
    {
        orders.Sort();
    }

    // 自定义排序
    public void SortOrders(Func<Order, Order, int> compareFunc)
    {
        orders.Sort((a, b) => compareFunc(a, b));
    }

    // 按总金额排序
    public void SortByTotalAmount()
    {
        orders.Sort((a, b) => a.TotalAmount.CompareTo(b.TotalAmount));
    }
}

class Program
{
    static void Main(string[] args)
    {
        OrderService orderService = new OrderService();

        // 创建一些测试数据
        var customer1 = new Customer("C001", "张三");
        var customer2 = new Customer("C002", "李四");

        var product1 = new Product("P001", "笔记本电脑", 5999m);
        var product2 = new Product("P002", "手机", 3999m);
        var product3 = new Product("P003", "耳机", 299m);

        while (true)
        {
            Console.WriteLine("\n订单管理系统");
            Console.WriteLine("1. 添加订单");
            Console.WriteLine("2. 删除订单");
            Console.WriteLine("3. 修改订单");
            Console.WriteLine("4. 查询订单");
            Console.WriteLine("5. 显示所有订单");
            Console.WriteLine("6. 排序订单");
            Console.WriteLine("0. 退出");
            Console.Write("请选择操作: ");

            string choice = Console.ReadLine();

            try
            {
                switch (choice)
                {
                    case "1": // 添加订单
                        AddOrder(orderService);
                        break;
                    case "2": // 删除订单
                        DeleteOrder(orderService);
                        break;
                    case "3": // 修改订单
                        UpdateOrder(orderService);
                        break;
                    case "4": // 查询订单
                        QueryOrders(orderService);
                        break;
                    case "5": // 显示所有订单
                        DisplayAllOrders(orderService);
                        break;
                    case "6": // 排序订单
                        SortOrders(orderService);
                        break;
                    case "0": // 退出
                        return;
                    default:
                        Console.WriteLine("无效的选择，请重新输入。");
                        break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发生错误: {ex.Message}");
            }
        }
    }

    static void AddOrder(OrderService orderService)
    {
        Console.Write("输入订单号: ");
        string orderId = Console.ReadLine();

        Console.Write("输入客户ID: ");
        string customerId = Console.ReadLine();
        Console.Write("输入客户姓名: ");
        string customerName = Console.ReadLine();
        var customer = new Customer(customerId, customerName);

        var order = new Order(orderId, customer, DateTime.Now);

        while (true)
        {
            Console.Write("是否添加商品明细? (y/n): ");
            if (Console.ReadLine().ToLower() != "y") break;

            Console.Write("输入商品ID: ");
            string productId = Console.ReadLine();
            Console.Write("输入商品名称: ");
            string productName = Console.ReadLine();
            Console.Write("输入商品价格: ");
            decimal price = decimal.Parse(Console.ReadLine());
            Console.Write("输入商品数量: ");
            int quantity = int.Parse(Console.ReadLine());

            var product = new Product(productId, productName, price);
            var detail = new OrderDetail(product, quantity);

            try
            {
                order.AddDetail(detail);
                Console.WriteLine("商品明细添加成功。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加商品明细失败: {ex.Message}");
            }
        }

        try
        {
            orderService.AddOrder(order);
            Console.WriteLine("订单添加成功。");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"添加订单失败: {ex.Message}");
        }
    }

    static void DeleteOrder(OrderService orderService)
    {
        Console.Write("输入要删除的订单号: ");
        string orderId = Console.ReadLine();

        try
        {
            orderService.RemoveOrder(orderId);
            Console.WriteLine("订单删除成功。");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"删除订单失败: {ex.Message}");
        }
    }

    static void UpdateOrder(OrderService orderService)
    {
        Console.Write("输入要修改的订单号: ");
        string orderId = Console.ReadLine();

        var existingOrders = orderService.QueryByOrderId(orderId);
        if (existingOrders.Count == 0)
        {
            Console.WriteLine("找不到指定的订单。");
            return;
        }

        Console.WriteLine("找到订单:");
        Console.WriteLine(existingOrders[0]);

        Console.Write("输入新的客户ID: ");
        string customerId = Console.ReadLine();
        Console.Write("输入新的客户姓名: ");
        string customerName = Console.ReadLine();
        var customer = new Customer(customerId, customerName);

        var updatedOrder = new Order(orderId, customer, DateTime.Now);

        while (true)
        {
            Console.Write("是否添加商品明细? (y/n): ");
            if (Console.ReadLine().ToLower() != "y") break;

            Console.Write("输入商品ID: ");
            string productId = Console.ReadLine();
            Console.Write("输入商品名称: ");
            string productName = Console.ReadLine();
            Console.Write("输入商品价格: ");
            decimal price = decimal.Parse(Console.ReadLine());
            Console.Write("输入商品数量: ");
            int quantity = int.Parse(Console.ReadLine());

            var product = new Product(productId, productName, price);
            var detail = new OrderDetail(product, quantity);

            try
            {
                updatedOrder.AddDetail(detail);
                Console.WriteLine("商品明细添加成功。");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"添加商品明细失败: {ex.Message}");
            }
        }

        try
        {
            orderService.UpdateOrder(updatedOrder);
            Console.WriteLine("订单修改成功。");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"修改订单失败: {ex.Message}");
        }
    }

    static void QueryOrders(OrderService orderService)
    {
        Console.WriteLine("\n查询选项:");
        Console.WriteLine("1. 按订单号查询");
        Console.WriteLine("2. 按商品名称查询");
        Console.WriteLine("3. 按客户查询");
        Console.WriteLine("4. 按金额范围查询");
        Console.Write("请选择查询方式: ");

        string queryChoice = Console.ReadLine();

        switch (queryChoice)
        {
            case "1":
                Console.Write("输入订单号: ");
                string orderId = Console.ReadLine();
                var ordersById = orderService.QueryByOrderId(orderId);
                DisplayOrders(ordersById);
                break;
            case "2":
                Console.Write("输入商品名称: ");
                string productName = Console.ReadLine();
                var ordersByProduct = orderService.QueryByProductName(productName);
                DisplayOrders(ordersByProduct);
                break;
            case "3":
                Console.Write("输入客户ID: ");
                string customerId = Console.ReadLine();
                Console.Write("输入客户姓名: ");
                string customerName = Console.ReadLine();
                var customer = new Customer(customerId, customerName);
                var ordersByCustomer = orderService.QueryByCustomer(customer);
                DisplayOrders(ordersByCustomer);
                break;
            case "4":
                Console.Write("输入最小金额: ");
                decimal minAmount = decimal.Parse(Console.ReadLine());
                Console.Write("输入最大金额: ");
                decimal maxAmount = decimal.Parse(Console.ReadLine());
                var ordersByAmount = orderService.QueryByAmountRange(minAmount, maxAmount);
                DisplayOrders(ordersByAmount);
                break;
            default:
                Console.WriteLine("无效的查询选项。");
                break;
        }
    }

    static void DisplayAllOrders(OrderService orderService)
    {
        var allOrders = orderService.GetAllOrders();
        DisplayOrders(allOrders);
    }

    static void DisplayOrders(List<Order> orders)
    {
        if (orders.Count == 0)
        {
            Console.WriteLine("没有找到符合条件的订单。");
            return;
        }

        Console.WriteLine($"\n找到 {orders.Count} 个订单:");
        foreach (var order in orders)
        {
            Console.WriteLine(order);
            Console.WriteLine("----------------------");
        }
    }

    static void SortOrders(OrderService orderService)
    {
        Console.WriteLine("\n排序选项:");
        Console.WriteLine("1. 按订单号排序");
        Console.WriteLine("2. 按总金额排序");
        Console.Write("请选择排序方式: ");

        string sortChoice = Console.ReadLine();

        switch (sortChoice)
        {
            case "1":
                orderService.SortOrders();
                Console.WriteLine("已按订单号排序。");
                break;
            case "2":
                orderService.SortByTotalAmount();
                Console.WriteLine("已按总金额排序。");
                break;
            default:
                Console.WriteLine("无效的排序选项。");
                break;
        }

        DisplayAllOrders(orderService);
    }
}
